package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Banner.ViewPagerAdapter;
import com.ydkj.a37e_mall.Classes.Model.Request.CommoditySelectReq;
import com.ydkj.a37e_mall.Classes.Model.Request.CreateStockReq;
import com.ydkj.a37e_mall.Classes.Model.Request.ProductDetailsReq;
import com.ydkj.a37e_mall.Classes.Model.Response.CommoditySelectResp;
import com.ydkj.a37e_mall.Classes.Model.Response.ProductDetailsResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.WrapContentHeightViewPager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.ydkj.a37e_mall.R.id.et_pop_commodity_number;

/**
 * Created by Administrator on 2017/2/15.
 * 申报商品==》商品详细
 */

public class CommodityDetails extends BaseActivity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView back;
    private WrapContentHeightViewPager vp_commodit_picture;
    private TextView tv_commodit_pic_num, tv_commodit_all_num, tv_commodit_name, tv_commodit_price, tv_commodit_color, tv_commodit_parameter, tv_commodit_close, tv_commodit_declare;
    private RelativeLayout rly_commodit_color, rly_commodit_parameter;

    private PopupWindow pop_typeSelect;//选择申报产品的数量
    private ImageView img_pop_commodit;
    private TextView tv_pop_commodit_name, tv_pop_commodit_close, tv_pop_commodit_declare;
    private ListView lv_pop_commodit;
    private PopselecttypeAdapter popselecttypeAdapter;
    private String id;
    private int currentIndex;
    private int bannerpage;
    private String thumb_url, product_name, store_id;
    private int number;
    private List<ProductDetailsResp.ResultEntity.DataEntity> bannerList;
    private List<CommoditySelectResp.ResultEntity.DataEntity> typeSelectInfoList;
    private List<String> idList;
    private List<String> numList;

    private String secret;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.commodity_details);
        mActivity = this;
        init();
        GetProductDeatls();
    }

    private void init() {

        if (this.getIntent().getExtras() != null) {
            id = getIntent().getExtras().getString("id");
            Log.e("ssss", "商品详情ID==》" + id);
        }

        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        back = (ImageView) mActivity.findViewById(R.id.img_back);

        tv_commodit_pic_num = (TextView) mActivity.findViewById(R.id.tv_commodit_pic_num);
        tv_commodit_all_num = (TextView) mActivity.findViewById(R.id.tv_commodit_all_num);
        tv_commodit_name = (TextView) mActivity.findViewById(R.id.tv_commodit_name);
        tv_commodit_price = (TextView) mActivity.findViewById(R.id.tv_commodit_price);
        tv_commodit_color = (TextView) mActivity.findViewById(R.id.tv_commodit_color);
        tv_commodit_parameter = (TextView) mActivity.findViewById(R.id.tv_commodit_parameter);
        tv_commodit_close = (TextView) mActivity.findViewById(R.id.tv_commodit_close);
        tv_commodit_declare = (TextView) mActivity.findViewById(R.id.tv_commodit_declare);

        rly_commodit_color = (RelativeLayout) mActivity.findViewById(R.id.rly_commodit_color);
        rly_commodit_parameter = (RelativeLayout) mActivity.findViewById(R.id.rly_commodit_parameter);

        bannerList = new ArrayList<ProductDetailsResp.ResultEntity.DataEntity>();
        typeSelectInfoList = new ArrayList<>();
        idList = new ArrayList<>();
        numList = new ArrayList<>();
        popselecttypeAdapter = new PopselecttypeAdapter(typeSelectInfoList);

        back.setOnClickListener(this);
        tv_commodit_close.setOnClickListener(this);
        tv_commodit_declare.setOnClickListener(this);
        rly_commodit_color.setOnClickListener(this);
        rly_commodit_parameter.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        WindowManager.LayoutParams lp;
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_commodit_close://关闭
                break;
            case R.id.tv_commodit_declare://申报商品

                Log.e("ssss", "idList.size()==>" + idList.size());
                if (idList.size() == 0) {
                    CommonUtil.showToast(mActivity, "请先选择申报的商品");
                    lp = getWindow().getAttributes();
                    lp.alpha = 0.3f;
                    getWindow().setAttributes(lp);
                    initTypeSelectPopupWindow();
                    pop_typeSelect.setAnimationStyle(R.style.popupWindowAnimation);
                    pop_typeSelect.showAtLocation(mActivity.findViewById(R.id.lly_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    pop_typeSelect.update();
                } else {
                    CreateStock();
                }
                break;
            case R.id.rly_commodit_color://产品参数选择
                lp = getWindow().getAttributes();
                lp.alpha = 0.3f;
                getWindow().setAttributes(lp);
                initTypeSelectPopupWindow();
                pop_typeSelect.setAnimationStyle(R.style.popupWindowAnimation);
                pop_typeSelect.showAtLocation(mActivity.findViewById(R.id.lly_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                pop_typeSelect.update();
                break;
            case R.id.rly_commodit_parameter://产品参数
                break;
        }
    }

    //获取商品详情
    private void GetProductDeatls() {
        CustomProgressDialog.createDialog(mActivity).Show();
        ProductDetailsReq req = new ProductDetailsReq();
        req.setId(id);
        if (!sharedPreferencesUtil.getAccessToken().equals("")) {
            params.put("token", sharedPreferencesUtil.getAccessToken());
        }

        try {
            String source = req.getSecret();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            Log.e("url", "source==" + source);

        } catch (Exception e) {
            e.printStackTrace();
        }

        params.put("secret", secret);

        String url = Const.COMMON_ADDRESS + req.urlString();
        Log.e("url", "url==" + url);
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "productDetail_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    ProductDetailsResp resp = GsonImpl.get().toObject(response.toString(), ProductDetailsResp.class);
                    bannerList.clear();
                    bannerList.add(resp.getResult().getData());
                    initBanner();

                    tv_commodit_name.setText(resp.getResult().getData().getList_title());
                    tv_commodit_price.setText(resp.getResult().getData().getPrice());

                    thumb_url = resp.getResult().getData().getList_thumb();
                    product_name = resp.getResult().getData().getName();


                    GetTypeSelect();
//                    GetProductParameter();
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //获取商品的制式
    private void GetTypeSelect() {
        CustomProgressDialog.createDialog(mActivity).show();
        CommoditySelectReq req = new CommoditySelectReq();
        req.setId(id);
        req.setUuid(myApplication.getDataEntity().getUuid());
        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            Log.e("url", "secret==" + secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.put("secret", secret);
        String url = Const.COMMON_ADDRESS + req.urlString();
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("ssss", "response==>" + response.toString());
                if (errno.equals("000")) {
                    CommoditySelectResp resp = GsonImpl.get().toObject(response.toString(), CommoditySelectResp.class);
                    typeSelectInfoList.clear();
                    typeSelectInfoList.addAll(resp.getResult().getData());
                    popselecttypeAdapter.notifyDataSetChanged();
                    StringBuffer buffer = new StringBuffer();
                    for (int i = 0; i < typeSelectInfoList.size(); i++) {
//                        buffer.append(typeSelectInfoList.get(i).getType() + " ");
                    }
//                    tv_commodit_color.setText("请选择" + " " + buffer.toString());
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    //申报商品
    private void CreateStock() {
        CustomProgressDialog.createDialog(mActivity).show();
        idList.clear();
        numList.clear();
        for (CommoditySelectResp.ResultEntity.DataEntity dataEntity : typeSelectInfoList) {
            if (dataEntity.getCheck_code() == 1) {
                idList.add(dataEntity.getId());
                numList.add(dataEntity.getNumber() + "");
            }
        }

        if (idList.size() == 0) {
            CommonUtil.showToast(mActivity, "请先选择申报的商品");
            return;
        }

        CreateStockReq req = new CreateStockReq();
        for (int i = 0; i < myApplication.getDataEntity().getStore_id().size(); i++) {
            store_id = myApplication.getDataEntity().getStore_id().get(i) + "";
        }
        Log.e("ssss", "商品id===》" + CommonUtil.listToString(idList, ','));
        Log.e("ssss", "商品数量===》" + CommonUtil.listToString(numList, ','));
        Log.e("ssss", "getStore_id===》" + store_id);
        Log.e("ssss", "token===》" + sharedPreferencesUtil.getAccessToken());


        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setProduct_id(id);
        req.setFormat_id_str(CommonUtil.listToString(idList, ','));
        req.setStock(CommonUtil.listToString(numList, ','));


        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            Log.e("ssss", "source==" + source);

        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = Const.COMMON_ADDRESS + req.urlString() + store_id;
        Log.e("ssss", "url==>" + url);

        RequestParams params = new RequestParams();
        params.put("store_id", store_id);
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", secret);
        Log.e("ssss", "secret==>" + secret);
        AsyncHttpClient client = new AsyncHttpClient();
        client.put(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("ssss", "response==>" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");

                if (errno.equals("000")) {
                    pop_typeSelect.dismiss();
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                Log.e("ssss", "statusCode==>" + statusCode);
                Log.e("ssss", "responseString==>" + responseString);
                CommonUtil.showToast(mActivity, "网络连接失败");

            }
        });
    }

    //商品viewpager图片
    private void initBanner() {
        List<View> bannerViews = new ArrayList<View>();
        for (int i = 0; i < bannerList.get(0).getAlbum().size(); i++) {
            final ProductDetailsResp.ResultEntity.DataEntity bannerInfo = bannerList.get(0);
            RelativeLayout bannerViewLayout = (RelativeLayout) LayoutInflater.from(mActivity).inflate(R.layout.product_details_scrollview_picture, null);
            ImageView img_product_picture = (ImageView) bannerViewLayout.findViewById(R.id.img_product_picture);

            ImageLoader.getInstance().displayImage(bannerInfo.getAlbum().get(i), img_product_picture);
            Log.e("rul", "getThumb====" + bannerList.size());
            Log.e("rul", "getThumb====" + bannerInfo.getAlbum().get(i));

            bannerViews.add(bannerViewLayout);
        }
        // 初始化banner
        tv_commodit_pic_num = (TextView) mActivity.findViewById(R.id.tv_commodit_pic_num);
        tv_commodit_all_num = (TextView) mActivity.findViewById(R.id.tv_commodit_all_num);

        if (bannerList.get(0).getAlbum().size() == 0) {
            tv_commodit_pic_num.setText("0");
        }

        tv_commodit_all_num.setText("" + bannerList.get(0).getAlbum().size());

        currentIndex = 0;
        bannerpage = 1;
        vp_commodit_picture = (WrapContentHeightViewPager) mActivity.findViewById(R.id.vp_commodit_picture);
        // 初始化Adapter
        ViewPagerAdapter bannerPagerAdapter = new ViewPagerAdapter(bannerViews);
        vp_commodit_picture.setAdapter(bannerPagerAdapter);
        vp_commodit_picture.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                currentIndex = arg0;
                int bannerIndex = arg0 + 1; // bannerIndex为第几张banner
                tv_commodit_pic_num.setText("" + bannerIndex);
                Log.e("bannerList.size()", "bannerList.size()==" + bannerList.size());
                bannerpage = arg0 + 1;
                if (bannerpage == bannerList.size()) {
                    bannerpage = 0;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
                vp_commodit_picture.getParent()
                        .requestDisallowInterceptTouchEvent(true);
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    //初始化产品属性的popupwindow
    private void initTypeSelectPopupWindow() {
        View contvent = LayoutInflater.from(mActivity).inflate(R.layout.pop_num_select, null);

        img_pop_commodit = (ImageView) contvent.findViewById(R.id.img_pop_commodit);
        tv_pop_commodit_name = (TextView) contvent.findViewById(R.id.tv_pop_commodit_name);
        tv_pop_commodit_close = (TextView) contvent.findViewById(R.id.tv_pop_commodit_close);
        tv_pop_commodit_declare = (TextView) contvent.findViewById(R.id.tv_pop_commodit_declare);
        lv_pop_commodit = (ListView) contvent.findViewById(R.id.lv_pop_commodit);


        ImageLoader.getInstance().displayImage(thumb_url, img_pop_commodit, displayImageOptions);
        tv_pop_commodit_name.setText(product_name);

        contvent.invalidate();
        pop_typeSelect = new PopupWindow(contvent, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置PopupWindow弹出窗体的背景
        pop_typeSelect.setBackgroundDrawable(dw);
        pop_typeSelect.setOutsideTouchable(true);
        pop_typeSelect.setFocusable(true);


        pop_typeSelect.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1;
                getWindow().setAttributes(lp);
            }
        });


        //关闭
        tv_pop_commodit_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop_typeSelect.dismiss();
            }
        });

        //申报商品
        tv_pop_commodit_declare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("ssss", "idList.size()==>" + idList.size());
//                if (idList.size() == 0) {
//                    CommonUtil.showToast(mActivity, "请先选择申报的商品");
////                    WindowManager.LayoutParams lp = getWindow().getAttributes();
////                    lp.alpha = 0.3f;
////                    getWindow().setAttributes(lp);
////                    initTypeSelectPopupWindow();
////                    pop_typeSelect.setAnimationStyle(R.style.popupWindowAnimation);
////                    pop_typeSelect.showAtLocation(mActivity.findViewById(R.id.lly_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
////                    pop_typeSelect.update();
//                } else {
                CreateStock();
//                }
            }
        });


        lv_pop_commodit.setAdapter(popselecttypeAdapter);
    }

    private class PopselecttypeAdapter extends BaseAdapter {
        private List<CommoditySelectResp.ResultEntity.DataEntity> poplist;

        private PopselecttypeAdapter(List<CommoditySelectResp.ResultEntity.DataEntity> info) {
            this.poplist = info;
        }

        @Override
        public int getCount() {
            return poplist.size();
        }

        @Override
        public CommoditySelectResp.ResultEntity.DataEntity getItem(int position) {
            return poplist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh = null;

            convertView = LayoutInflater.from(mActivity).inflate(R.layout.pop_commodity_type_list, null);
            vh = new ViewHolder();
            vh.img_pop_commodity = (ImageView) convertView.findViewById(R.id.img_pop_commodity);
            vh.tv_pop_commodity_name = (TextView) convertView.findViewById(R.id.tv_pop_commodity_name);
            vh.tv_pop_commodity_price = (TextView) convertView.findViewById(R.id.tv_pop_commodity_price);
            vh.tv_pop_commodity_less = (TextView) convertView.findViewById(R.id.tv_pop_commodity_less);
            vh.tv_pop_commodity_add = (TextView) convertView.findViewById(R.id.tv_pop_commodity_add);
            vh.et_pop_commodity_number = (EditText) convertView.findViewById(et_pop_commodity_number);


            convertView.setTag(vh);
            convertView.setClickable(true);
            vh.tv_pop_commodity_name.setText(getItem(position).getName());
            vh.tv_pop_commodity_price.setText("¥ " + getItem(position).getPrice());

            vh.et_pop_commodity_number.setText(getItem(position).getNumber() + "");

            if (getItem(position).getCheck_code() == 0) {
                vh.img_pop_commodity.setBackground(getResources().getDrawable(R.mipmap.round_select_no));
            } else if (getItem(position).getCheck_code() == 1) {
                vh.img_pop_commodity.setBackground(getResources().getDrawable(R.mipmap.round_select_yes));

            }

            //选择
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (getItem(position).isFlag()) {
                        getItem(position).setCheck_code(1);
                        getItem(position).setFlag(false);
                        Log.e("ssss", "convertView1111");
                    } else {
                        getItem(position).setCheck_code(0);
                        getItem(position).setFlag(true);
                        Log.e("ssss", "convertView2222");
                    }

                    popselecttypeAdapter.notifyDataSetChanged();
                }
            });

            //增加
            final ViewHolder finalVh = vh;
            vh.tv_pop_commodity_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    number = getItem(position).getNumber();
                    number++;
                    finalVh.et_pop_commodity_number.setText(number + "");
                    getItem(position).setNumber(number);
                }
            });

            //减少
            vh.tv_pop_commodity_less.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    number = getItem(position).getNumber();

                    if (number == 1) {
                        return;
                    } else {
                        number = getItem(position).getNumber();
                        number--;
                        finalVh.et_pop_commodity_number.setText(number + "");
                        getItem(position).setNumber(number);
                    }
                }
            });

            vh.et_pop_commodity_number.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    if (charSequence.toString().equals("")) {
                        getItem(position).setNumber(1);
                    } else {
                        getItem(position).setNumber(Integer.parseInt(charSequence.toString()));

                    }
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (editable.toString().equals("")) {
                        getItem(position).setNumber(1);
                    } else {
                        getItem(position).setNumber(Integer.parseInt(editable.toString()));

                    }
                }
            });
            return convertView;
        }

        private class ViewHolder {
            private ImageView img_pop_commodity;
            private TextView tv_pop_commodity_name, tv_pop_commodity_price, tv_pop_commodity_less, tv_pop_commodity_add;
            private EditText et_pop_commodity_number;
        }
    }


}


